import sqlite3
import os
import logging
from logging_config import setup_logging
from werkzeug.security import generate_password_hash

# 获取应用根目录
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

# 配置日志
setup_logging(APP_ROOT)
sync_logger = logging.getLogger('sync')

# 数据库文件路径
DB_PATH = os.path.join('db', 'sync.db')

def get_db_connection():
    """获取数据库连接"""
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def init_db():
    """初始化数据库"""
    try:
        # 确保db目录存在
        os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
        
        sync_logger.info(f"使用数据库路径: {DB_PATH}")
        sync_logger.info(f"数据库文件是否存在: {os.path.exists(DB_PATH)}")
        
        conn = get_db_connection()
        
        # 创建用户表
        conn.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT UNIQUE NOT NULL,
                password TEXT NOT NULL
            )
        ''')
        
        # 创建同步目录表
        conn.execute('''
            CREATE TABLE IF NOT EXISTS sync_dirs (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                local_path TEXT NOT NULL,
                ftp_path TEXT NOT NULL,
                ftp_host TEXT NOT NULL,
                ftp_port INTEGER NOT NULL,
                ftp_user TEXT NOT NULL,
                ftp_password TEXT NOT NULL,
                sync_strategy TEXT NOT NULL,
                status TEXT DEFAULT 'running',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        
        # 创建同步历史表
        conn.execute('''
            CREATE TABLE IF NOT EXISTS sync_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                sync_dir_id INTEGER NOT NULL,
                file_path TEXT NOT NULL,
                operation TEXT NOT NULL,
                sync_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (sync_dir_id) REFERENCES sync_dirs (id)
            )
        ''')
        
        conn.commit()
        conn.close()
        
        sync_logger.info(f"数据库初始化完成，路径: {DB_PATH}")
        return True
    except Exception as e:
        sync_logger.error(f"初始化数据库失败: {str(e)}")
        return False

def create_default_user():
    """创建默认用户（如果不存在）"""
    try:
        conn = get_db_connection()
        cursor = conn.execute('SELECT * FROM users WHERE username = ?', ('admin',))
        if not cursor.fetchone():
            conn.execute(
                'INSERT INTO users (username, password) VALUES (?, ?)',
                ('admin', generate_password_hash('admin'))
            )
            conn.commit()
        conn.close()
    except Exception as e:
        sync_logger.error(f"创建默认用户失败: {str(e)}")

# 初始化数据库
init_db()
create_default_user() 